package com.wfw.second.controller;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.ClusterFlowConfig;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowSlot;
import com.wfw.common.pojo.TestVo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @ Author     ：duanchao
 * @ Date       ： 14:35 2021/1/7
 * @ Description：
 */

@RestController
@RequestMapping("/sentinel")
public class SentinelTestController {

    @RequestMapping("/test")
    @SentinelResource(value = "sentinel-test",blockHandler = "blockHandlerTest" ,fallback = "fallbackTest")
    public String sentinelTest(TestVo testVo){

//        int i = 1 / 0;


        return  "test sentinel1";

    }



    // Block 异常处理函数，参数最后多一个 BlockException，其余与原函数一致.
    public static String blockHandlerTest(TestVo testVo, BlockException ex) {
        // Do some log here.
        System.out.println("***************************** 进入异常·");
        System.out.println(testVo);
        ex.printStackTrace();
        return "Oops, error occurred at " ;
    }


    public String fallbackTest ( TestVo testVo,Throwable e){
        System.out.println("***************************** fallbackTest·");
        System.out.println(testVo);
        e.printStackTrace();
        return "Oops, fallbackTest " ;
    }


    @RequestMapping("/custom")
    public String sentinelTest(){
        List<FlowRule> flowRules = new ArrayList<>();
        FlowRule flowRule = new FlowRule();
        //直接拒绝、Warm Up、匀速排队
        flowRule.setControlBehavior(0);
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        flowRule.setCount(1D);
        flowRule.setStrategy(0);
        flowRule.setResource("custom-test");
        flowRules.add(flowRule);
        FlowRuleManager.loadRules(flowRules);

        try(Entry entry = SphU.entry("custom-test")) {
            System.out.println( "ceshi qps");

        }catch (BlockException e){
            System.out.println("异常");
        }

        return "";
    }

}